package www.yingdi365.com.fragment;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;

import www.yingdi365.com.R;
import www.yingdi365.com.activity.BianJiQJActivity;
import www.yingdi365.com.activity.BianJiQJYLActivity;
import www.yingdi365.com.activity.XiuGaiQJWZActivity;
import www.yingdi365.com.base.ZjbBaseFragment;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.model.QingJianBean;
import www.yingdi365.com.model.XiuGaiQJWZ;
import www.yingdi365.com.photoview.PhotoView;
import www.yingdi365.com.util.DpUtils;

/**
 * A simple {@link Fragment} subclass.
 */
public class QingJianBJYLFragment extends ZjbBaseFragment {


    private View mInflate;
    private QingJianBean pagesBean;
    private AbsoluteLayout viewAbsolute;
    private ImageView imageBg;
    private TextView[] textViews;
    private PhotoView[] imageViews;
    //    private ImageView[] imageViews0;
    private int position;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case Constant.BROADCASTCODE.QingJianBaoCun:
                    int positionGG = intent.getIntExtra(Constant.INTENT_KEY.Position, -1);
                    if (positionGG == position) {
                        pagesBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
                        refreashViews();
                    }
                    break;
                case Constant.BROADCASTCODE.XiuGaiQJWZ:
                    int positionGG1 = intent.getIntExtra(Constant.INTENT_KEY.Position, -1);
                    if (positionGG1 == position) {
                        pagesBean = (QingJianBean) intent.getSerializableExtra(Constant.INTENT_KEY.pagesBean);
                        refreashViews();
                    }
                    break;
            }
        }
    };
    private float baiFenBiWidth;
    private float baiFenBiHeigh;
    private View viewBianJi;

    private void refreashViews() {
        showLoadingDialog();
        viewAbsolute.removeAllViews();
        initUI();
        cancelLoadingDialog();
    }

    public QingJianBJYLFragment() {
        // Required empty public constructor
    }

    public QingJianBJYLFragment(QingJianBean pagesBean, int position) {
        // Required empty public constructor
        this.pagesBean = pagesBean;
        this.position = position;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (mInflate == null) {
            mInflate = inflater.inflate(R.layout.fragment_qing_jian_zz, container, false);
            init();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) mInflate.getParent();
        if (parent != null) {
            parent.removeView(mInflate);
        }
        return mInflate;
    }

    @Override
    protected void initIntent() {
        for (int i = 0; i < pagesBean.getItems().size(); i++) {
            QingJianBean.ItemsBeanX itemsBeanX = pagesBean.getItems().get(i);
            itemsBeanX.setIndex(i);
        }
        textViews = new TextView[pagesBean.getItems().size()];
        imageViews = new PhotoView[pagesBean.getItems().size()];
//        imageViews0 = new ImageView[pagesBean.getItems().size()];
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void findID() {
        viewAbsolute = (AbsoluteLayout) mInflate.findViewById(R.id.viewAbsolute);
        imageBg = (ImageView) mInflate.findViewById(R.id.imageBg);
        viewBianJi = mInflate.findViewById(R.id.viewBianJi);
    }

    @Override
    protected void initViews() {
        try {
            viewAbsolute.setBackgroundColor(Color.parseColor(pagesBean.getBgColor()));
        } catch (Exception e) {
        }
        if (pagesBean.getItems().size() == 0 && TextUtils.isEmpty(pagesBean.getBgImage())) {
            Glide.with(getActivity())
                    .load(pagesBean.getPreview())
                    .into(imageBg);
        } else {
            viewAbsolute.post(new Runnable() {
                public void run() {
                    int width = viewAbsolute.getWidth();
                    int height = viewAbsolute.getHeight();//height is ready
                    baiFenBiWidth = (float) width / 640f;
                    baiFenBiHeigh = (float) height / 920f;
                    initUI();
                    Glide.with(getActivity())
                            .load(pagesBean.getBgImage())
                            .into(imageBg);
                }
            });
        }
    }

    private void initUI() {
        for (int i = 0; i < pagesBean.getItems().size(); i++) {
            final QingJianBean.ItemsBeanX itemsBean = pagesBean.getItems().get(i);
            switch (itemsBean.getType()) {
                case "picture":
                    final QingJianBean.ItemsBeanX.PictureBeanX pictureBean = itemsBean.getPicture();
                    float vx = (float) (pictureBean.getVx()) * baiFenBiWidth;
                    float vy = (float) (pictureBean.getVy()) * baiFenBiHeigh;
                    float vWidth = (float) (pictureBean.getVwidth()) * baiFenBiWidth;
                    float vHeight = (float) (pictureBean.getVheight()) * baiFenBiHeigh;
                    imageViews[itemsBean.getIndex()] = new PhotoView(getActivity());
                    imageViews[itemsBean.getIndex()].setLayoutParams(new AbsoluteLayout.LayoutParams((int) vWidth, (int) vHeight, (int) vx, (int) vy));
                    imageViews[itemsBean.getIndex()].setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(getActivity())
                            .load(pictureBean.getUrl()+Constant.TuPianYaSuo).listener(new RequestListener<String, GlideDrawable>() {
                        @Override
                        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                            if (itemsBean.isDiy()) {
                                float scaleW = (float) (pictureBean.getWidth()) / (float) (pictureBean.getVwidth());
                                float scaleH = (float) (pictureBean.getHeight()) / (float) (pictureBean.getVheight());
                                float scale = scaleH > scaleW ? scaleW : scaleH;
                                imageViews[itemsBean.getIndex()].zoomToQuick(scale, (float) (pictureBean.getX() - pictureBean.getVx()) * baiFenBiWidth, (float) (pictureBean.getY() - pictureBean.getVy()) * baiFenBiHeigh);
                            }
                            return false;
                        }
                    })
                            .into(new SimpleTarget<GlideDrawable>() {
                                @Override
                                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
                                    imageViews[itemsBean.getIndex()].setImageDrawable(resource);
                                }
                            });
                    viewAbsolute.addView(imageViews[itemsBean.getIndex()]);
                    break;
                case "text":
                    QingJianBean.ItemsBeanX.TextBeanX textBeanX = itemsBean.getText();
                    float vx1 = (float) (textBeanX.getX()) * baiFenBiWidth;
                    float vy1 = (float) (textBeanX.getY()) * baiFenBiHeigh;
                    float vWidth1 = (float) (textBeanX.getWidth()) * baiFenBiWidth;
                    float vHeight1 = (float) (textBeanX.getHeight()) * baiFenBiHeigh * 1.2f;
                    textViews[itemsBean.getIndex()] = new TextView(getActivity());
                    textViews[itemsBean.getIndex()].setLayoutParams(new AbsoluteLayout.LayoutParams((int) vWidth1, (int) vHeight1, (int) vx1, (int) vy1 - (int) (0.3f * vHeight1)));
                    textViews[itemsBean.getIndex()].setTextSize(DpUtils.convertPixelsToDp(Float.parseFloat(textBeanX.getFontSize()) * baiFenBiWidth, getActivity()));
                    textViews[itemsBean.getIndex()].setGravity(Gravity.CENTER);
                    textViews[itemsBean.getIndex()].setText(textBeanX.getContent());
                    textViews[itemsBean.getIndex()].setBackgroundResource(R.drawable.shape_edittext_bianji_3dp);
                    viewAbsolute.addView(textViews[itemsBean.getIndex()]);
                    break;
            }
        }
    }

    @Override
    protected void setListeners() {
        viewBianJi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                if (position == 0) {
                    intent.setClass(getActivity(), XiuGaiQJWZActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.XiuGaiQJWZ, new XiuGaiQJWZ(
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getBoy(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getBoyMobile(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getGirl(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getGirlMobile(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getTreatDate(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getHotel(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getTreatAddress(),
                            ((BianJiQJYLActivity) getActivity()).appInvitation.getTreatAddressLocation()
                    ));
                    intent.putExtra(Constant.INTENT_KEY.pagesBean, pagesBean);
                    intent.putExtra(Constant.INTENT_KEY.Position, position);
                    startActivity(intent);
                } else {
                    intent.setClass(getActivity(), BianJiQJActivity.class);
                    intent.putExtra(Constant.INTENT_KEY.pagesBean, pagesBean);
                    intent.putExtra(Constant.INTENT_KEY.Position, position);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void initData() {
    }

    @Override
    public void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.QingJianBaoCun);
        filter.addAction(Constant.BROADCASTCODE.XiuGaiQJWZ);
        getActivity().registerReceiver(receiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }
}
